
import re
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from appengine_utilities.flash import Flash



class RequestHandler(webapp.RequestHandler):
  
  urls = {}
  
  def get(self):
    if not self.findAction('get'):
      self.not_found()
    
  def post(self):
    if not self.findAction('post'):
      self.not_found()
  
  
  
  def findAction(self, method):
    path = self.request.path
    kwargs = {}
    action = ''
    
    if path in self.urls:
      action = self.urls[path]
    else:
      for k, v in self.urls.items():
        if path + '/' == k:
          self.redirect(k, permanent=True)
          return True
        
        if not k.count(':'):
          continue
        
        pattern = '^' + re.sub(':(\\w+)', '(?P<\\1>[^/]+)', k) + '$'
        match = re.search(pattern, path)
        if match:
          kwargs = match.groupdict()
          action = v
          break
    
    if not action:
      return False
    
    # we have a match, now get the right action for the method
    if isinstance(action, str):
      if method != 'get':
        self.not_allowed()
        return True
    elif method in action:
      action = action[method]
    else:
      self.not_allowed()
      return True
    
    # the action might be a redirect
    if action[0] == '/':
      self.redirect(action, permanent=True)
      return True
    
    if hasattr(self, action) and callable(getattr(self, action)):
      getattr(self, action)(**kwargs)
    else:
      self.server_error()
    
    return True
      
  
  
  def is_admin(self):
    return users.get_current_user() != None
  
  
  def require_admin(self):
    is_admin = self.is_admin()
    if not is_admin:
      self.redirect(users.create_login_url())
    return is_admin
  
  
  def render(self, template_file, vars = {}):
    vars['flash'] = Flash()
    self.response.out.write(webapp.template.render('templates/%s' % template_file, vars))
    
  def render_source(self, template_source, vars = {}):
    t = webapp.template.Template(template_source)
    self.response.out.write(t.render(webapp.template.Context(vars)))
    
  def user_error(self, msg, redirect = ''):
    flash = Flash()
    flash.msg = 'Error: ' + msg
    return self.redirect(redirect)
  
  def user_msg(self, msg, redirect = ''):
    flash = Flash()
    flash.msg = msg
    return self.redirect(redirect)
  
  def get_portstr(self):
    url = self.request.url
    port = url[url.find(':', 6):]
    return port[0:port.find('/')]
  
  def server_error(self):
    self.error(500)
    self.render('500.html')
  
  def not_allowed(self):
    self.error(405)
    self.render('405.html')
  
  def not_found(self):
    self.error(404)
    self.render('404.html')
  
  